package com.adingxiong.quickstart.project.controller;


import com.adingxiong.quickstart.project.entity.SysLog;
import com.adingxiong.quickstart.project.service.ISysLogService;
import com.adingxiong.quickstart.result.Result;
import com.adingxiong.quickstart.result.RetCode;
import com.adingxiong.quickstart.util.GetRealIp;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统日志 前端控制器
 * </p>
 *
 * @author xiongc
 * @since 2020-05-28
 */
@RestController
@RequestMapping("/sys-log")
@Api(tags = "网站日志模块")
public class SysLogController {
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    @Autowired
    private ISysLogService logService;

    @ApiOperation(value = "用于自己自动记录网站访问的日志")
    @PostMapping("/saveLog")
    public Result saveLogs (HttpServletRequest request,
                            @ApiParam(value = "访问类型 1. 附件下载 2. 网站浏览",required = true) @RequestParam(value = "type") Integer type){
        String ip = GetRealIp.getIpaddr(request);
        if(StringUtils.isEmpty(ip)){
            return new Result(RetCode.SYSTEM_ERROR.getCode(),RetCode.SYSTEM_ERROR.getMsg(),false);
        }

        if(StringUtils.isEmpty(type)){
            return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),false);
        }
        //查询当前ip今日是否访问过
        Date date = new Date();
        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();

        Map<String,Object> params = new HashMap<>();

        params.put("type",type);
        params.put("ip_address",ip);
        queryWrapper.allEq(params).gt("create_time",sdf.format(date));

        SysLog res = logService.getOne(queryWrapper,false);
        if(res == null){

            //今日查看不到  查看历史记录 并访问次数+1
            QueryWrapper<SysLog> query = new QueryWrapper<>();
            query.eq("type",type).eq("ip_address",ip);
            SysLog sysLog = logService.getOne(query,false);
            if(sysLog != null){
                //存在数据  对之前数进行修改操作
                if(type == 1){
                    sysLog.setUploadCount(sysLog.getUploadCount() + 1);
                }else{
                    sysLog.setViewcCount(sysLog.getViewcCount() +1);
                }
                boolean update = logService.updateById(sysLog);
                return new Result(update ? RetCode.SUCCESS.getCode() : RetCode.SYSTEM_ERROR.getCode(),update ? "记录成功" : "记录失败",update);
            }
            SysLog insert = new SysLog();
            //不存在改数据   数据新增
            insert.setCreateTime(LocalDateTime.now());
            insert.setCreator("admin");
            insert.setIpAddress(ip);
            insert.setType(type);
            String userAgent = request.getHeader("User-Agent");
            insert.setClientVersion(userAgent);

            if(type == 1){
                insert.setUploadCount(1);
            }else{
                insert.setViewcCount(1);
            }
            boolean inser = logService.save(insert);
            return new Result(inser ? RetCode.SUCCESS.getCode() : RetCode.SYSTEM_ERROR.getCode(),inser ? "记录成功" : "记录失败",inser);
        }

        return new Result(RetCode.SUCCESS.getCode(),"当前IP已记录",false);
    }


    @ApiOperation(value = "模糊查询")
    @GetMapping("/list")
    public Result<Page<SysLog>> getList(
            @ApiParam(value = "ip地址" ) @RequestParam(value = "ip",required = false) String ip,
            @ApiParam(value = "当前页面", defaultValue = "1") @RequestParam(value = "current",defaultValue = "1") Integer current,
            @ApiParam(value = "每页条数" , defaultValue = "10") @RequestParam(value = "size",defaultValue = "10") Integer size
    ){
        Page<SysLog> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);
        QueryWrapper<SysLog> query = new QueryWrapper<>();
        if(!StringUtils.isEmpty(ip)){
           query.eq("ip_address" ,ip);
        }
        Page<SysLog> res = logService.page(page,query);
        return new Result(RetCode.SUCCESS.getCode(),RetCode.SUCCESS.getMsg(),res);

    }


    @GetMapping("/del")
    @ApiOperation(value = "根据id删除数据")
    public Result del(
            @ApiParam(value = "主键",required = true) @RequestParam(value = "id")Integer id
    ){
        if(StringUtils.isEmpty(id)){
            return new Result(RetCode.PARAM_ERROR.getCode(),RetCode.PARAM_ERROR.getMsg(),false);
        }
        boolean del = logService.removeById(id);
        return new Result(del ? RetCode.SUCCESS.getCode() : RetCode.SYSTEM_ERROR.getCode(),del ? "删除成功" : "删除失败",del);
    }

}

